#!/usr/bin/env python3
"""
航班管理系统简化测试脚本
直接测试API端点和核心功能
"""

import sys
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

def test_system_startup():
    """测试系统启动"""
    print("🚀 测试航班管理系统启动...")
    
    try:
        from app.main import app
        from fastapi.testclient import TestClient
        
        client = TestClient(app)
        
        # 测试根路径
        response = client.get("/")
        print(f"✅ 根路径测试: {response.status_code}")
        
        # 测试健康检查
        response = client.get("/health")
        print(f"✅ 健康检查: {response.status_code}")
        
        return True
    except Exception as e:
        print(f"❌ 系统启动测试失败: {e}")
        return False

def test_database_operations():
    """测试数据库操作"""
    print("\n🗄️ 测试数据库操作...")
    
    try:
        # 创建测试数据库
        test_db = project_root / "test_simple.db"
        if test_db.exists():
            test_db.unlink()
        
        from tests.database import Base, engine
        Base.metadata.create_all(bind=engine)
        
        # 测试模型导入
        from app.models.flight import Flight
        from app.models.passenger import Passenger
        from app.models.booking import Booking
        
        print("✅ 数据库模型导入成功")
        
        # 测试创建会话
        from tests.database import SessionLocal
        db = SessionLocal()
        
        # 测试创建航班
        flight = Flight(
            flight_number="TEST001",
            departure_city="北京",
            arrival_city="上海",
            departure_time="2024-12-25 08:00:00",
            arrival_time="2024-12-25 10:00:00",
            price=1000.00,
            total_seats=200,
            available_seats=150
        )
        db.add(flight)
        db.commit()
        
        print(f"✅ 创建测试航班成功: {flight.flight_number}")
        
        # 查询航班
        flights = db.query(Flight).all()
        print(f"✅ 查询航班成功: {len(flights)} 条记录")
        
        db.close()
        return True
        
    except Exception as e:
        print(f"❌ 数据库测试失败: {e}")
        return False

def test_api_endpoints():
    """测试API端点"""
    print("\n🔗 测试API端点...")
    
    try:
        from app.main import app
        from fastapi.testclient import TestClient
        
        client = TestClient(app)
        
        # 测试航班API
        response = client.get("/flights/")
        print(f"✅ 航班列表API: {response.status_code}")
        
        # 测试乘客API
        response = client.get("/passengers/")
        print(f"✅ 乘客列表API: {response.status_code}")
        
        # 测试预订API
        response = client.get("/bookings/")
        print(f"✅ 预订列表API: {response.status_code}")
        
        # 测试统计API
        response = client.get("/reports/flight-load-rate")
        print(f"✅ 载客率统计API: {response.status_code}")
        
        response = client.get("/reports/revenue")
        print(f"✅ 收入统计API: {response.status_code}")
        
        return True
        
    except Exception as e:
        print(f"❌ API测试失败: {e}")
        return False

def test_service_layer():
    """测试服务层"""
    print("\n⚙️ 测试服务层...")
    
    try:
        from tests.database import SessionLocal
        from app.services.flight_service import FlightService
        from app.services.passenger_service import PassengerService
        from app.services.booking_service import BookingService
        from app.services.report_service import ReportService
        
        db = SessionLocal()
        
        # 测试航班服务
        flight_service = FlightService(db)
        flights = flight_service.get_all_flights()
        print(f"✅ 航班服务正常: {len(flights)} 条记录")
        
        # 测试乘客服务
        passenger_service = PassengerService(db)
        passengers = passenger_service.get_all_passengers()
        print(f"✅ 乘客服务正常: {len(passengers)} 条记录")
        
        # 测试预订服务
        booking_service = BookingService(db)
        bookings = booking_service.get_all_bookings()
        print(f"✅ 预订服务正常: {len(bookings)} 条记录")
        
        # 测试报表服务
        report_service = ReportService(db)
        try:
            load_rate = report_service.get_flight_load_rate_stats()
            print(f"✅ 载客率统计服务正常: {len(load_rate)} 条记录")
            
            revenue = report_service.get_revenue_stats()
            print(f"✅ 收入统计服务正常: {len(revenue)} 条记录")
            
        except Exception as e:
            print(f"⚠️ 报表服务测试: {e}")
        
        db.close()
        return True
        
    except Exception as e:
        print(f"❌ 服务层测试失败: {e}")
        return False

def main():
    """主测试流程"""
    print("🎯 航班管理系统重新测试")
    print("=" * 50)
    
    tests = [
        ("系统启动测试", test_system_startup),
        ("数据库操作测试", test_database_operations),
        ("API端点测试", test_api_endpoints),
        ("服务层测试", test_service_layer),
    ]
    
    passed = 0
    total = len(tests)
    
    for test_name, test_func in tests:
        print(f"\n📋 {test_name}")
        try:
            if test_func():
                passed += 1
                print(f"✅ {test_name} 通过")
            else:
                print(f"❌ {test_name} 失败")
        except Exception as e:
            print(f"❌ {test_name} 异常: {e}")
    
    print("\n" + "=" * 50)
    print(f"📊 测试结果: {passed}/{total} 项测试通过")
    
    if passed == total:
        print("🎉 所有测试通过！航班管理系统运行正常")
        print("\n🚀 系统已准备就绪，可以开始部署")
    else:
        print("⚠️ 部分测试未通过，请检查具体错误信息")
    
    # 清理测试文件
    try:
        test_files = ["test_simple.db", "test_reports.db", "test_bookings.db", "test.db"]
        for file in test_files:
            file_path = project_root / file
            if file_path.exists():
                file_path.unlink()
                print(f"🧹 清理了 {file}")
    except:
        pass

if __name__ == "__main__":
    main()